package com.masterclient.app.modules.main.widget;


import android.app.Dialog;
import android.content.Context;
import android.graphics.Rect;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.widget.NestedScrollView;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.eoner.baselib.presenter.ThrowableConsumer;
import com.eoner.baselibrary.utils.ScreenUtils;
import com.eoner.baselib.utils.toast.ToastUtil;
import com.masterclient.app.R;
import com.masterclient.app.httpservice.RetrofitUtil2;
import com.eoner.baselib.container.CommonBaseResponse;
import com.masterclient.app.modules.main.adapter.ScanWelfareAdapter;
import com.masterclient.app.modules.main.beans.ScanReceiveBean;
import com.masterclient.app.modules.main.beans.ScanWelfareDataBean;
import com.masterclient.app.modules.main.beans.ScanWelfareItemBean;
import com.masterclient.app.modules.main.manager.ScanManager;

import org.json.JSONException;
import org.json.JSONObject;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
import okhttp3.RequestBody;

/**
 * @auther hjian
 * @date 2020/7/27.
 */
public class ScanWelfareDialog extends Dialog {

    @BindView(R.id.dialog_scan_welfare_scroll)
    NestedScrollView dialogScanWelfareScroll;
    @BindView(R.id.dialog_scan_welfare_close)
    ImageView dialogScanWelfareClose;
    @BindView(R.id.dialog_scan_welfare_recycler)
    RecyclerView dialogScanWelfareRecycler;
    @BindView(R.id.dialog_scan_welfare_coupon_line)
    View dialogScanWelfareCouponLine;
    @BindView(R.id.dialog_scan_welfare_subtitle)
    TextView dialogScanWelfareSubtitle;
    @BindView(R.id.dialog_scan_welfare_subtitle_layout)
    FrameLayout dialogScanWelfareSubtitleLayout;
    @BindView(R.id.dialog_scan_welfare_coupon)
    RecyclerView dialogScanWelfareCoupon;
    @BindView(R.id.dialog_scan_welfare_shadow)
    ImageView dialogScanWelfareShadow;
    @BindView(R.id.dialog_scan_welfare_receive)
    ImageView dialogScanWelfareReceive;
    @BindView(R.id.dialog_scan_welfare_head)
    ImageView dialogScanWelfareHead;

    private Context mContext;
//    private ConfirmCallback confirmCallback;
    private ScanWelfareDataBean dataBean;
    private ScanWelfareAdapter welfareAdapter, couponAdapter;
    private String code;

//    public interface ConfirmCallback{
//        void onConfirm(Dialog dialog);
//    }

    public ScanWelfareDialog(@NonNull Context context,String code,ScanWelfareDataBean dataBean) {
        super(context);
        mContext = context;
        this.code = code;
        this.dataBean = dataBean;
//        this.confirmCallback = confirmCallback;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.dialog_scan_welfare);
        ButterKnife.bind(this);
        setCanceledOnTouchOutside(false);

        dialogScanWelfareShadow.setVisibility((dataBean.getFixed_list() != null &&dataBean.getFixed_list().size()>3)
                || (dataBean.getSales_rule_list() != null && dataBean.getSales_rule_list().size()>=3) || (dataBean.
                getSales_rule_list() != null && dataBean.getSales_rule_list().size()<=0 && dataBean.getFixed_list() != null
                &&dataBean.getFixed_list().size()<=0&& (dataBean.getFixed_list().size()
                +dataBean.getSales_rule_list().size() >= 3))?View.VISIBLE:View.GONE);
        if (dialogScanWelfareShadow.getVisibility() == View.VISIBLE){
            dialogScanWelfareScroll.getLayoutParams().height = ScreenUtils.dp2px(236);
        }

        if (dataBean.getFixed_list() != null && dataBean.getFixed_list().size()>0){
            welfareAdapter = new ScanWelfareAdapter(false);
            dialogScanWelfareRecycler.setLayoutManager(new LinearLayoutManager(mContext){
                @Override
                public boolean canScrollVertically() {
                    return false;
                }
            });
            dialogScanWelfareRecycler.addItemDecoration(new RecyclerView.ItemDecoration() {
                @Override
                public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
                    super.getItemOffsets(outRect, view, parent, state);
                    if (parent.getChildAdapterPosition(view) != dataBean.getFixed_list().size()-1)
                    outRect.bottom = ScreenUtils.dp2px(10);
                }
            });
            dialogScanWelfareRecycler.setAdapter(welfareAdapter);
            welfareAdapter.setNewData(dataBean.getFixed_list());
        }else {
            dialogScanWelfareRecycler.setVisibility(View.GONE);
            dialogScanWelfareCouponLine.setVisibility(View.VISIBLE);
        }

        if (dataBean.getSales_rule_list() != null && dataBean.getSales_rule_list().size()>0){
            dialogScanWelfareSubtitleLayout.setVisibility(View.VISIBLE);
            dialogScanWelfareCoupon.setVisibility(View.VISIBLE);
            couponAdapter = new ScanWelfareAdapter(true);
            dialogScanWelfareCoupon.setLayoutManager(new LinearLayoutManager(mContext){
                @Override
                public boolean canScrollVertically() {
                    return false;
                }
            });
            dialogScanWelfareCoupon.addItemDecoration(new RecyclerView.ItemDecoration() {
                @Override
                public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
                    super.getItemOffsets(outRect, view, parent, state);
                    outRect.bottom = ScreenUtils.dp2px(10);
                }
            });
            dialogScanWelfareCoupon.setAdapter(couponAdapter);
            couponAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
                @Override
                public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                    if (!couponAdapter.getData().get(position).isIs_sold_out())
                    couponAdapter.setSelectIndex(position);
                }
            });
            couponAdapter.setNewData(dataBean.getSales_rule_list());
            if (isDefaultSelectCoupon()){
                couponAdapter.setSelectIndex(defaultSelectPos);
            }
        }

    }

    int defaultSelectPos = -1;

    /**
     * 是否只有一个可选的，默认选中
     * @return
     */
    private boolean isDefaultSelectCoupon(){
        int haveNumCoupon = 0;
        for (int i = 0; i < dataBean.getSales_rule_list().size(); i++) {
            ScanWelfareItemBean item = dataBean.getSales_rule_list().get(i);
                if (!item.isIs_sold_out()){
                    defaultSelectPos = i;
                    ++haveNumCoupon;
                }
            }
        return haveNumCoupon == 1;
    }

    @Override
    protected void onStart() {
        super.onStart();
        Window window = getWindow();
        WindowManager.LayoutParams windowparams = window.getAttributes();
        windowparams.width = ScreenUtils.getScreenWidth();
        windowparams.height = WindowManager.LayoutParams.WRAP_CONTENT;
        window.setGravity(Gravity.CENTER);
        window.setBackgroundDrawableResource(R.color.transparent);
        window.setType(WindowManager.LayoutParams.TYPE_APPLICATION_PANEL);
        window.setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);

        window.setAttributes(windowparams);
    }

    @OnClick({R.id.dialog_scan_welfare_close, R.id.dialog_scan_welfare_receive})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.dialog_scan_welfare_close:
                dismiss();
                break;
            case R.id.dialog_scan_welfare_receive:
                dialogScanWelfareReceive.setEnabled(false);
                    receiveCoupon(ScanManager.getScanManager().code, couponAdapter==null||couponAdapter.getSelectIndex() == -1 ? "" :
                            couponAdapter.getData().get(couponAdapter.getSelectIndex()).getRule_id());
                break;
        }
    }

    Disposable disposable;

    /**
     * 领取优惠券
     * @param code
     * @param sales_rule_id
     */
    private void receiveCoupon(String code, String sales_rule_id){

        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("code",code);
            jsonObject.put("sales_rule_id", sales_rule_id);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        RequestBody body = RequestBody.create(okhttp3.MediaType.parse("application/json; charset=utf-8"),
                jsonObject.toString());
        disposable = RetrofitUtil2.getInstance().scanReceive(body).subscribeOn(Schedulers.io())
                .unsubscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<CommonBaseResponse<ScanReceiveBean>>() {
                    @Override
                    public void accept(CommonBaseResponse<ScanReceiveBean> bean) throws Exception {
                        if (bean.getCode() == 0) {
                            ToastUtil.showToast(bean.getData().getMsg());
                            if ("0".equals(bean.getData().getReceive_type())){
                                ScanWelfareDialog.this.dismiss();
                            }else {
                                couponAdapter.getData().get(couponAdapter.getSelectIndex()).setIs_sold_out(true);
                                if (isDefaultSelectCoupon()){
                                    couponAdapter.setSelectIndex(defaultSelectPos);
                                }
                            }
                        } else {
                            ToastUtil.showToast(bean.getMsg());
                        }
                        dialogScanWelfareReceive.setEnabled(true);
                    }
                }, new ThrowableConsumer(){
                    @Override
                    public void accept(Throwable o) throws Exception {
                        super.accept(o);
                        ToastUtil.showToast("网络异常，请检查您的网络");
                        dialogScanWelfareReceive.setEnabled(true);
                    }
                });
    }

    @Override
    public void dismiss() {
        super.dismiss();
        if (disposable != null) {
            disposable.dispose();
            disposable = null;
        }
        ScanManager.getScanManager().welfareBean = null;
        ScanManager.getScanManager().code = null;
        ScanManager.getScanManager().welfareSuccessDialog = null;
    }
}
